﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aga.Psad.Backend.Entities;
using Aga.Psad.Common;

namespace Aga.Psad.Backend.Repositories
{
    public class RepositoryBase<T>
        where T : class, IDomainEntity
    {

        public RepositoryBase()
        {
            CheckDatabase();
        }

        private PsadDataContext dc;
        public PsadDataContext DC
        {
            get
            {
                if (dc == null)
                    dc = new PsadDataContext(Config.AgaConnectionString);

                return dc;
            }
        }

        private void CheckDatabase()
        {
            if (!DC.DatabaseExists())
                DC.CreateDatabase();
        }

        public List<T> GetAll()
        {
            var table = DC.GetTable<T>();

            var query = from e in table
                        select e;

            return query.ToList();
        }

        public IQueryable<T> GetPage(int pageIndex, int pageSize)
        {
            var table = DC.GetTable<T>();

            var query = from e in table
                        select e;

            return query.Skip(pageIndex*pageSize).Take(pageSize);
        }

        public int Count()
        {
            var table = DC.GetTable<T>();

            var query = from e in table
                        select e;

            return query.Count();
        }

        public int Count(Func<T,bool> where)
        {
            var table = DC.GetTable<T>();

            var query = from e in table
                        select e;

            return query.Where(where).Count();
        }

        public T GetById(int id)
        {
            var table = DC.GetTable<T>();

            var entity = table.Where(e => e.Id.Equals(id)).SingleOrDefault();

            return entity;
        }

        public void Save(T entity)
        {
            var table = DC.GetTable<T>();

            if (entity.Id.Equals(0))
                table.InsertOnSubmit(entity);

            DC.SubmitChanges();
        }

        public void Delete(T entity)
        {
            var table = DC.GetTable<T>();

            table.DeleteOnSubmit(entity);

            DC.SubmitChanges();
        }
    }
}
